/**
 * @author：balthie + 10050
 * @createtime ： 2015年2月10日 下午2:55:24
 * @description TODO 一句话描述
 */
package com.common.exception;

import com.common.consts.CommonRespCode;
import com.common.dto.BaseResp;
import com.common.dto.SpringBootResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: zhaojd1604@gmail.com
 * @date: 2019-01-02 16:42
 * @description: 通用业务异常处理器
 * @since: V0.0.1
 */
@ControllerAdvice
public class CommonExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ExceptionHandler(value = {Exception.class})
    protected SpringBootResp doResolveException(HttpServletRequest request,
                                                HttpServletResponse response, Exception ex) {

        if (logger.isDebugEnabled()) {
            logger.debug("doResolveException invoke");
        }
        String errorMsg;
        BaseResp resp;
        String paramsString = request.getQueryString();
        if (ex instanceof CommonException) {
            CommonException commonExcp = (CommonException) ex;
            resp = new BaseResp(commonExcp);
            errorMsg = String.format(" 捕获业务异常，错误信息 : code【%d】 desc【%s】 with queryString【%s】",
                    commonExcp.getResponseCode(), commonExcp.getMessage(), paramsString);
            logger.warn(errorMsg, ex.getMessage());
        } else {
            resp = new BaseResp(CommonRespCode.SERVER_EXCEPTION);
            errorMsg = String.format(" 捕获未知异常,  code【%d】 desc【%s】 with queryString【%s】 ：",
                    CommonRespCode.SERVER_EXCEPTION.getCode(), CommonRespCode.SERVER_EXCEPTION.getMessage(), paramsString);
            logger.error(errorMsg, ex);
        }
        // 设置允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        logger.debug(" doResolveException end ");
        return new SpringBootResp(resp);
    }
}